<template>
  <div class="unit-manage-container">
    <div class="table-box">
      <!-- 搜索表单 -->
      <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
        <el-form-item label="单位编码" prop="unitCode">
          <el-input v-model="searchForm.unitCode" placeholder="请输入单位编码" clearable />
        </el-form-item>
        <el-form-item label="单位名称" prop="unitName">
          <el-input v-model="searchForm.unitName" placeholder="请输入单位名称" clearable />
        </el-form-item>
        <el-form-item label="单位类型" prop="unitType">
          <el-select v-model="searchForm.unitType" placeholder="请选择单位类型" clearable style="width: 150px">
            <el-option label="数量" value="数量" />
            <el-option label="重量" value="重量" />
            <el-option label="长度" value="长度" />
            <el-option label="面积" value="面积" />
            <el-option label="体积" value="体积" />
            <el-option label="时间" value="时间" />
            <el-option label="温度" value="温度" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="table-header">
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增单位</el-button>
        <el-button type="danger" :icon="Delete" @click="batchDelete" :disabled="!multipleSelection.length">批量删除</el-button>
        <el-button type="success" :icon="Download" @click="handleExport">导出</el-button>
      </div>

      <el-table 
        :data="tableData" 
        style="width: 100%" 
        v-loading="loading" 
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="unitCode" label="单位编码" width="120" />
        <el-table-column prop="unitName" label="单位名称" width="150" />
        <el-table-column prop="unitSymbol" label="单位符号" width="100" />
        <el-table-column prop="unitType" label="单位类型" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.unitType">{{ scope.row.unitType }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="isBaseUnit" label="基础单位" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isBaseUnit === 1 ? 'success' : 'info'">
              {{ scope.row.isBaseUnit === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="conversionFactor" label="换算系数" width="120">
          <template #default="scope">
            {{ scope.row.conversionFactor || 1.0000 }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="100" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
            <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDeleteUnit(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <UnitDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="ts" name="unitManage">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, Delete, EditPen, Download, View } from "@element-plus/icons-vue";
import UnitDrawer from "@/views/unitManage/UnitDrawer.vue";
import { UnitManage } from "@/api/interface";
import { getUnitList, deleteUnit, batchDeleteUnit } from "@/api/modules/unitManage";

// 搜索表单
const searchForm = reactive({
  unitCode: "",
  unitName: "",
  unitType: "",
  status: undefined as number | undefined
});

// 表格数据
const tableData = ref<UnitManage.ResUnitList[]>([]);
const loading = ref(false);
const multipleSelection = ref<UnitManage.ResUnitList[]>([]);

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

// 获取表格数据
const getTableList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      ...searchForm
    };
    const { data } = await getUnitList(params);
    tableData.value = data.records;
    pagination.total = data.total;
    pagination.current = data.current;
    pagination.size = data.size;
  } catch (error) {
    console.error("获取单位列表失败:", error);
    ElMessage.error("获取单位列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  getTableList();
};

// 重置
const searchFormRef = ref();
const handleReset = () => {
  searchFormRef.value?.resetFields();
  pagination.current = 1;
  getTableList();
};

// 分页处理
const handleSizeChange = (val: number) => {
  pagination.size = val;
  pagination.current = 1;
  getTableList();
};

const handleCurrentChange = (val: number) => {
  pagination.current = val;
  getTableList();
};

// 多选处理
const handleSelectionChange = (val: UnitManage.ResUnitList[]) => {
  multipleSelection.value = val;
};

// 删除单位
const handleDeleteUnit = async (row: UnitManage.ResUnitList) => {
  try {
    await ElMessageBox.confirm(`确认删除单位【${row.unitName}】吗？`, "温馨提示", {
      type: "warning"
    });
    await deleteUnit({ id: row.id });
    ElMessage.success("删除成功");
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除单位失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 批量删除
const batchDelete = async () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条数据吗？`, "温馨提示", {
      type: "warning"
    });
    const ids = multipleSelection.value.map(item => item.id);
    await batchDeleteUnit({ ids });
    ElMessage.success("批量删除成功");
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除失败:", error);
      ElMessage.error("批量删除失败");
    }
  }
};

// 打开抽屉
const drawerRef = ref<InstanceType<typeof UnitDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<UnitManage.ResUnitList> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    getTableList
  };
  drawerRef.value?.acceptParams(params);
};

// 导出
const handleExport = () => {
  ElMessage.info("导出功能开发中...");
};

// 初始化
onMounted(() => {
  getTableList();
});
</script>

<style scoped lang="scss">
.unit-manage-container {
  padding: 20px;
  
  .table-box {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    
    .search-form {
      margin-bottom: 20px;
      padding: 20px;
      background: #f8f9fa;
      border-radius: 6px;
      
      .el-form-item {
        margin-bottom: 0;
      }
    }
    
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .el-button {
        margin-right: 10px;
        
        &:last-child {
          margin-right: 0;
        }
      }
    }
    
    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }
}
</style>